<?php
namespace app\admin\controller;

use app\admin\model\ClothmakingRecipeProducts;
use app\common\controller\Backend;
use think\Exception;
use think\facade\Db;

class ClothmakingRecipeProductsController extends Backend
{
    // 定义模型
    protected $model = null;

    // 无需登录的方法
    protected $noNeedLogin = [];

    // 无需鉴权的方法
    protected $noNeedRight = [];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\ClothmakingRecipeProducts;
    }

    /**
     * 查看产品配方列表
     */
    public function index()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            return 'aaa';
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['recipe', 'product']) // 预加载关联
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 添加产品配方
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            Db::startTrans();
            try {
                // 验证数据
                $result = $this->validate($params, [
                    'recipe_id' => 'require|number',
                    'product_id' => 'require|number',
                ]);

                if (true !== $result) {
                    throw new Exception($result);
                }

                // 保存数据
                $model = $this->model;
                $model->save($params);

                Db::commit();
                $this->success();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        return $this->view->fetch();
    }

    /**
     * 编辑产品配方
     */
    public function edit($ids = null)
    {
        $row = $this->model->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            Db::startTrans();
            try {
                // 验证数据
                $result = $this->validate($params, [
                    'recipe_id' => 'require|number',
                    'product_id' => 'require|number',
                ]);

                if (true !== $result) {
                    throw new Exception($result);
                }

                // 更新数据
                $row->save($params);

                Db::commit();
                $this->success();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除产品配方
     */
    public function del($ids = "")
    {
        if ($ids) {
            $ids = explode(',', $ids);

            Db::startTrans();
            try {
                $count = 0;
                foreach ($ids as $id) {
                    $row = $this->model->find($id);
                    if ($row) {
                        $row->delete();
                        $count++;
                    }
                }

                Db::commit();
                $this->success("成功删除{$count}条记录");
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 批量更新
     */
    public function multi($ids = '')
    {
        $ids = $ids ? explode(',', $ids) : [];

        if ($this->request->isPost()) {
            $params = $this->request->post('params/a');

            Db::startTrans();
            try {
                $count = 0;
                foreach ($ids as $id) {
                    $row = $this->model->find($id);
                    if ($row) {
                        $row->save($params);
                        $count++;
                    }
                }

                Db::commit();
                $this->success("成功更新{$count}条记录");
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 根据配方ID获取产品列表
     */
    public function getByRecipe($recipe_id)
    {
        $list = $this->model
            ->with(['product'])
            ->where('recipe_id', $recipe_id)
            ->select();

        $this->success('', null, $list);
    }
}